package com.choichumgming.rentcat.service.Impl;

import com.alibaba.fastjson.JSON;
import com.choichumgming.rentcat.common.api.CommonResult;
import com.choichumgming.rentcat.dto.MemberDetails;
import com.choichumgming.rentcat.mapper.UmsMemberMapper;
import com.choichumgming.rentcat.model.UmsMember;
import com.choichumgming.rentcat.model.UmsMemberExample;
import com.choichumgming.rentcat.security.util.JwtTokenUtil;
import com.choichumgming.rentcat.service.RedisService;
import com.choichumgming.rentcat.service.UmsMemberService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 会员管理Service实现类
 */
@Service
@Slf4j
public class UmsMemberServiceImpl implements UmsMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UmsMemberMapper memberMapper ;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;


    /**
     * @Description : 根据用户名获取会员
     *
     * @param username
     * @Return : com.choichumgming.rentcat.model.UmsMember
     * @Author : choichumgming
     * @Date : 16/3/2020 15:35
    */

    @Override
    public UmsMember getByUsername(String username) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            return memberList.get(0);
        }
        return null;
    }

    /**
     * @Description : 根据会员编号获取会员
     *
     * @param id
     * @Return : com.choichumgming.rentcat.model.UmsMember
     * @Author : choichumgming
     * @Date : 16/3/2020 15:35
    */
    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }


    /**
     * @Description : 用户注册
     *
     * @param username
     * @param password
     * @param telephone
     * @param authCode
     * @Return : com.choichumgming.rentcat.common.api.CommonResult
     * @Author : choichumgming
     * @Date : 16/3/2020 15:35
    */
    @Override
    public Map<String, String>  register(String username, String password, String telephone, String authCode) {
        //验证验证码
        Map<String, String> tokenMap = new HashMap<>();

        if(!verifyAuthCode(authCode,telephone)){
            log.warn("手机：{} 验证码：{}", telephone, authCode);
            tokenMap.put("status", "failed");
            return tokenMap;
        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            log.warn("该用户已经存在");
            tokenMap.put("status", "failed");
            return tokenMap;
        }
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setPhone(telephone);
//        密码加密
        umsMember.setPassword(passwordEncoder.encode(password));
        umsMember.setCreateTime(new Date());
//        默认设置积分
        umsMember.setIntegration(0);
//        设置默认前面
        umsMember.setDescription("这个人什么也没留下");
        umsMember.setIcon("https://rentcatapp.oss-cn-shanghai.aliyuncs.com/img/xiaoxin.jpeg");
        umsMember.setStatus(1);
        memberMapper.insert(umsMember);

        MemberDetails userDetails = loadUserByUsername(username);
//
//           配置认证
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(userDetails);
        tokenMap.put("token", tokenHead+" "+token);
        tokenMap.put("user", JSON.toJSONString(umsMember));
        tokenMap.put("status", "success");
        return tokenMap;
    }

    /**生成验证码
     * 在这部将验证码绑定手机号
     * @param telephone
     * @return
     */
    @Override
    public CommonResult generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        //验证码绑定手机号并存储到redis
        redisService.set(REDIS_KEY_PREFIX_AUTH_CODE+telephone, sb.toString());

        redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE+telephone,AUTH_CODE_EXPIRE_SECONDS);
        log.info("手机{}获取验证码为：{}",REDIS_KEY_PREFIX_AUTH_CODE+telephone ,sb.toString());
        return CommonResult.success(sb.toString(),"获取验证码成功");
    }


    /**
     * @Description : 修改密码
     *
     * @param telephone
     * @param password
     * @param authCode
     * @Return : com.choichumgming.rentcat.common.api.CommonResult
     * @Author : choichumgming
     * @Date : 16/3/2020 15:35
    */
    @Override
    public CommonResult updatePassword(String telephone, String password, String authCode) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(memberList)){
            return CommonResult.failed("该账号不存在");
        }
        //验证验证码
        if(!verifyAuthCode(authCode,telephone)){
            return CommonResult.failed("验证码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(passwordEncoder.encode(password));

        memberMapper.updateByPrimaryKeySelective(umsMember);
        return CommonResult.success(null,"密码修改成功");
    }

    /**
     * @Description : 获取当前登录会员
     *
     * @Return : com.choichumgming.rentcat.model.UmsMember
     * @Author : choichumgming
     * @Date : 16/3/2020 15:36
    */
    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        MemberDetails memberDetails = ((CommonResult<MemberDetails>) auth.getPrincipal()).getData();
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(memberDetails.getUsername());
        memberMapper.selectByExample(example);
        return memberMapper.selectByExample(example).get(0);
    }

    /**
     * @Description : 根据会员id修改会员积分
     *
     * @param id
     * @param integration
     * @Return : int
     * @Author : choichumgming
     * @Date : 16/3/2020 15:36
    */
    @Override
    public int updateIntegration(Long id, Integer integration) {
        UmsMember record=new UmsMember();
        record.setUserId(id);
        record.setIntegration(integration);
        return  memberMapper.updateByPrimaryKeySelective(record);
    }


    /**
     * @Description : 账号密码登录
     *  然后获取token
     *
     * @param username
     * @param password
     * @Return : java.lang.String
     * @Author : choichumgming
     * @Date : 16/3/2020 15:36
    */
    @Override
    public Map<String, String> pwdLogin(String username, String password) {
        //密码需要客户端加密后传递
        Map<String, String> tokenMap = new HashMap<>();
        try {
            MemberDetails userDetails = loadUserByUsername(username);
            if(userDetails.getUmsMember() == null){
                tokenMap.put("status", "failed");
                return tokenMap;
            }
//            密码不正确
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                tokenMap.put("status", "failed");
                return tokenMap;
            }
//           配置认证
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String token = jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token", tokenHead+" "+token);
            tokenMap.put("user", JSON.toJSONString(userDetails.getUmsMember()));
            tokenMap.put("status", "success");
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }

//        UmsMemberExample example = new UmsMemberExample();
//        example.createCriteria().andUsernameEqualTo(username);
//        List<UmsMember> memberList = memberMapper.selectByExample(example);
//        if (memberList.size()>0){
//            if( passwordEncoder.matches(password,memberList.get(0).getPassword())){
//                return CommonResult.success(memberList.get(0));
//            }else {
//                return CommonResult.validateFailed("登录失败");
//            }
//        }else {
//            return CommonResult.validateFailed("登录失败");
//        }
        return tokenMap;
    }

    /**
     * @Description : sms登录
     *
     * @param tel
     * @param auth
     * @Return : java.lang.String
     * @Author : choichumgming
     * @Date : 16/3/2020 15:43
    */
    @Override
    public Map<String, String> smsLogin(String tel, String auth) {
        Map<String, String> tokenMap = new HashMap<>();

        if (!verifyAuthCode(auth, tel)){
            tokenMap.put("status", "failed");
            return  tokenMap;
        }else {
            UmsMemberExample example = new UmsMemberExample();
            example.createCriteria().andPhoneEqualTo(tel);
            UmsMember member = memberMapper.selectByExample(example).get(0);
            MemberDetails userDetails = new MemberDetails();
            userDetails.setUmsMember(member);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String token = jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token", tokenHead+" "+token);
            tokenMap.put("user",JSON.toJSONString(member));
            tokenMap.put("status", "success");
            return tokenMap;
        }
    }

    //    @Override
//    public String refreshToken(String token) {
//        return jwtTokenUtil.refreshHeadToken(token);
//    }

    /**
     * @Description : 对输入的验证码进行校验
     *
     * @param authCode
     * @param telephone
     * @Return : boolean
     * @Author : choichumgming
     * @Date : 16/3/2020 15:36
    */
    private boolean verifyAuthCode(String authCode, String telephone){
        if(StringUtils.isEmpty(authCode)){
            return false;
        }
        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE + telephone);
        return authCode.equals(realAuthCode);
    }

    /**
     * @Description : 根据username获得用户信息
     *
     * @param username
     * @Return : com.choichumgming.rentcat.dto.MemberDetails
     * @Author : choichumgming
     * @Date : 16/3/2020 15:36
    */
    @Override
    public MemberDetails loadUserByUsername(String username) {
        UmsMember member = getByUsername(username);

        return new MemberDetails(member);

//        throw new UsernameNotFoundException("用户名或密码错误");
    }
}
